<script setup lang="ts">
import { computed, defineEmits, defineProps, onMounted, reactive, ref, shallowRef, watch } from 'vue'
import { Modal, message } from 'ant-design-vue'
import { EditOutlined } from '@ant-design/icons-vue'
import type { MenuModel } from '~@/api/menu/menu'
import { detailApi, tree, updateApi } from '~@/api/menu/menu'

// 定义props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  menuId: {
    type: String,
    required: true,
  },
})

// 定义emits
const emit = defineEmits(['update:visible', 'close'])

// 直接使用ant-design-vue提供的message全局对象
// 不需要创建实例，直接使用导入的message对象
const loading = shallowRef(false)
const menuTree = shallowRef<MenuModel[]>([])

// 当前编辑的菜单ID
const currentMenuId = computed(() => props.menuId)

const formModel = reactive<MenuModel>({
  menuName: '',
  menuCode: '',
  menuSort: 0,
  statusFlag: 0,
  remark: '',
  antdvRouter: '',
  antdvComponent: '',
  antdvIcon: '',
  menuId: 0,
  menuParentId: 0,
  versionFlag: 0,
  delFlag: 'N',
  antdvLinkUrl: '',
  antdvActiveUrl: '',
  antdvVisible: '',
})

// 获取菜单详情
async function fetchMenuDetail() {
  if (!currentMenuId.value)
    return

  loading.value = true
  try {
    const { data } = await detailApi(currentMenuId.value)
    Object.assign(formModel, data)
    // 确保菜单详情加载完成后再获取菜单树
    if (formModel.menuId) {
      await fetchMenuTree()
    }
  }
  catch (error) {
    console.error('获取菜单详情失败:', error)
    message.error('获取菜单详情失败，请重试')
  }
  finally {
    loading.value = false
  }
}

// 获取菜单树数据
async function fetchMenuTree() {
  try {
    const { data } = await tree()
    // 过滤掉当前菜单及其子菜单，避免选择自己作为父菜单
    const filterTree = (treeData: MenuModel[]) => {
      return treeData.filter(item => item.menuId !== formModel.menuId).map(item => ({
        ...item,
        children: item.children ? filterTree(item.children) : undefined,
      }))
    }
    menuTree.value = filterTree(data.list ?? [])
  }
  catch (error) {
    console.error('获取菜单树失败:', error)
  }
}

// 提交表单更新菜单
async function handleSubmit() {
  if (loading.value)
    return

  // 简单验证
  if (!formModel.menuName.trim()) {
    message.error('菜单名称不能为空')
    return
  }

  if (!formModel.menuCode.trim()) {
    message.error('菜单编码不能为空')
    return
  }

  loading.value = true
  try {
    const res = await updateApi(formModel)
    if (res.code === 200) {
      message.success('修改成功')
      // 关闭弹窗
      emit('update:visible', false)
      emit('close')
    }
  }
  catch (error) {
    console.error('修改菜单失败:', error)
    message.error('修改失败，请重试')
  }
  finally {
    loading.value = false
  }
}

// 取消操作
function handleCancel() {
  emit('update:visible', false)
  emit('close')
}

// 当弹窗打开时重新获取数据
watch(() => props.visible, (newVisible) => {
  if (newVisible) {
    fetchMenuDetail()
  }
})
</script>

<template>
  <Modal
    v-model:visible="props.visible"
    title="修改菜单"
    :footer="null"
    @cancel="handleCancel"
    @open="fetchMenuDetail"
  >
    <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
      <a-form-item label="菜单名称" required>
        <a-input v-model:value="formModel.menuName" placeholder="请输入菜单名称" />
      </a-form-item>

      <a-form-item label="菜单编码" required>
        <a-input v-model:value="formModel.menuCode" placeholder="请输入菜单编码" />
      </a-form-item>

      <a-form-item label="父菜单">
        <a-tree-select
          v-model:value="formModel.menuParentId"
          :tree-data="menuTree"
          :field-names="{ label: 'menuName', value: 'menuId', children: 'children' }"
          placeholder="请选择父菜单"
          allow-clear
        />
      </a-form-item>

      <a-form-item label="排序">
        <a-input-number v-model:value="formModel.menuSort" min="0" placeholder="请输入排序号" />
      </a-form-item>

      <a-form-item label="路由地址">
        <a-input v-model:value="formModel.antdvRouter" placeholder="请输入路由地址" />
      </a-form-item>

      <a-form-item label="组件路径">
        <a-input v-model:value="formModel.antdvComponent" placeholder="请输入组件路径" />
      </a-form-item>

      <a-form-item label="图标编码">
        <a-input v-model:value="formModel.antdvIcon" placeholder="请输入图标编码" />
      </a-form-item>

      <a-form-item label="是否显示">
        <a-radio-group v-model:value="formModel.antdvVisible">
          <a-radio value="Y">
            是
          </a-radio>
          <a-radio value="N">
            否
          </a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item label="外部链接地址">
        <a-input v-model:value="formModel.antdvLinkUrl" placeholder="请输入外部链接地址" />
      </a-form-item>

      <a-form-item label="重定向URL">
        <a-input v-model:value="formModel.antdvActiveUrl" placeholder="请输入重定向URL" />
      </a-form-item>

      <a-form-item label="备注">
        <a-textarea v-model:value="formModel.remark" placeholder="请输入备注信息" :rows="3" />
      </a-form-item>

      <a-form-item :wrapper-col="{ offset: 6 }">
        <a-space>
          <a-button :loading="loading" type="primary" @click="handleSubmit">
            <template #icon>
              <EditOutlined />
            </template>
            修改
          </a-button>
          <a-button @click="handleCancel">
            取消
          </a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </Modal>
</template>

<style scoped>
  :deep(.ant-card) {
    margin-bottom: 16px;
  }
</style>
